package com.nondo.rdp.finance.service.impl;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.UserFollow;
import com.nondo.rdp.finance.repository.UserFollowRepository;
import com.nondo.rdp.finance.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class UserFollowServiceImpl implements UserFollowService {
    @Autowired
    UserFollowRepository userFollowRepository;

    @Override
    public UserFollow save(UserFollow userFollow) {
        return this.userFollowRepository.save(userFollow);
    }

    @Override
    public void delete(Long id) {
        this.userFollowRepository.deleteById(id);
    }

    @Override
    public Page<UserFollow> findAll(Page<UserFollow> page, UserFollow userFollow) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<UserFollow> dictPage = userFollowRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<UserFollow>(dictPage);
    }

    @Override
    public UserFollow findByFollowerAndUser(User follower, User user) {
        return this.userFollowRepository.findByFollowerAndUser(follower, user);
    }
}